package com.wjz.admin.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wjz.commons.entity.bo.AjaxResult;
import com.wjz.commons.entity.vo.RuleVo;
import com.wjz.commons.enums.MasterConstants;
import com.wjz.commons.service.RuleApiService;
import com.wjz.commons.util.ResultTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author wjz
 * @date 2021/9/8 21:03
 */
@RestController
@RequestMapping("/rule")
public class RuleApiController {

    @Autowired
    private RuleApiService ruleApiService;

    @PostMapping
    public AjaxResult save(@RequestBody RuleVo ruleVo) {
        Long objectId = IdUtil.getSnowflake().nextId();
        ruleVo.setObjectId(objectId)
                .setName("rule_" + objectId)
                .setStatus(MasterConstants.OPEN);
        return ResultTool.success(ruleApiService.save(ruleVo.setCreateTime(new Date())));
    }

    @PutMapping
    public AjaxResult update(@RequestBody RuleVo ruleVo) {
        return ResultTool.success(ruleApiService.updateById(ruleVo.setUpdateTime(new Date())));
    }

    @GetMapping
    public AjaxResult queryAllRule(Long modelId, Long activationId) {
        return ResultTool.success(ruleApiService.list(new LambdaQueryWrapper<RuleVo>()
                .eq(RuleVo::getModelId, modelId)
                .eq(RuleVo::getActivationId, activationId)));
    }

    @DeleteMapping("/deleteById/{objectId}")
    public AjaxResult deleteById(@PathVariable Long objectId) {
        return ResultTool.success(ruleApiService.removeById(objectId));
    }

    @GetMapping("/disable")
    public AjaxResult disable(Long objectId, Integer status) {
        ruleApiService.updateById(new RuleVo().setObjectId(objectId)
                .setStatus(status == 1 ? MasterConstants.CLOSE : MasterConstants.OPEN));
        return ResultTool.success();
    }
}
